#include <lib/holyhttp.h>
#include <utils/string.h>
#include <utils/address.h>
#include <utils/dbapi.h>
#include "cgi.h"
#include "comment.h"
#include "guest.h"

static db_table_t comments = {0};
static db_col_t comment_cols[CMT_COL_NUM] = {
    DB_COL_SET_INT(CMT_COL_BLOG, CMT_COLNAME_BLOG),
    DB_COL_SET_INT(CMT_COL_GUEST, "guest"),
    DB_COL_SET_STR(CMT_COL_IP, "ip", IP_STR_LEN),
    DB_COL_SET_STR(CMT_COL_CONTENT, "content", CMT_CONTENT_LEN),
    DB_COL_SET_STR(CMT_COL_CREATED_TIME, CMT_COLNAME_CREATED_TIME, TIME_STR_LEN),
    DB_COL_SET_INT(CMT_COL_ACTIVE, "active"),
};

int get_comments(int blog_id, db_result_t *result)
{
    char condition[64] = {0};
    char *order_by = "`"CMT_COLNAME_CREATED_TIME"` DESC";

    snprintf(condition, sizeof condition, "`%s`=%d AND active=1", CMT_COLNAME_BLOG, blog_id);
    return comments.select(&comments, condition, order_by, 0, 0, result);
}

void cgi_add_comment(holyreq_t *req)
{
    db_value_t values[CMT_COL_NUM] = {0};
    char *name = NULL, *key = NULL, *comment = NULL, *blog = NULL;
    int gid = 0;

    if (req->method != POST_METHOD) {
        req->send_status(req, METHOD_NOT_ALLOWED);
        return;
    }
    
    blog = req->get_arg(req, "blog");
    name = req->get_arg(req, "name");
    key = req->get_arg(req, "key");
    comment = req->get_arg(req, "comment");
    if (!name || !key || !comment || !blog ||
        !name[0] || !key[0] || !comment[0] || !blog[0]) {
        req->send_status(req, BAD_REQUEST);
        return;
    }
    gid = get_guest_id(name, key);
    if (!gid) {
        req->send_html(req, AJAX_FAIL_FMT, "密钥不对");
        return;
    }

    values[CMT_COL_BLOG].i = atoi(blog);
    values[CMT_COL_GUEST].i = gid;
    values[CMT_COL_IP].s = IPV4_BIN_TO_STR(req->ip);
    values[CMT_COL_CREATED_TIME].s = get_datetime_str();
    values[CMT_COL_ACTIVE].i = 1;
    values[CMT_COL_CONTENT].s = base64enc(comment);
    if (!values[CMT_COL_CONTENT].s) {
        req->send_status(req, INTERNAL_ERROR);
        return;
    }

    if (!comments.add(&comments, values)) {
        req->send_status(req, INTERNAL_ERROR);
    } else {
        req->send_html(req, AJAX_SUCCESS_FMT, "发表成功");
    }

    free(values[CMT_COL_CONTENT].s);
}

void cgi_del_comment(holyreq_t *req)
{
    char *id = req->get_arg(req, "id");
    int result = 0;

    if (!id) {
        req->send_status(req, BAD_REQUEST);
        return;
    }

#if 1
    if (comments.set_col(&comments, atoi(id), CMT_COL_ACTIVE, (db_value_t)1)) {
        result = 1;
    }
#else
    if (comments.del(&comments, atoi(id))) {
        result = 1;
    }
#endif

    if (result) {
        req->send_html(req, AJAX_SUCCESS_FMT, "删除成功");
    } else {
        req->send_status(req, INTERNAL_ERROR);
    }
}

void init_comment(void)
{
    db_table_init(DEF_SQLITE3_DB, &comments, "comment", comment_cols, ARRAY_SIZE(comment_cols));
}

